<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { queryFoodList, insertFood, updateFood, deleteFood } from '@/api/food'
import AdminTable from '@/components/table/index.vue'
import { foodColumns, foodTypeMap, foodLoveTypeMap } from './const'
import type { FoodInstanceInterface, FoodFormType } from '@/types/views/food'
import type { FormInstance, FormRules } from 'element-plus'

// 请求数据列表
const keyword = ref<string>('')
const foodList = ref<FoodInstanceInterface[]>([])
const initQueryList = async () => {
    const response = await queryFoodList({ keyword: keyword.value })
    if (!response) return
    foodList.value = response.map((item) => {
        return {
            ...item,
            foodTypeView: foodTypeMap[item.foodType],
            foodLoveView: foodLoveTypeMap[item.loveType]
        }
    })
}
initQueryList()

// 条件查询
const selectOptions = ref<any[]>([])
const selected = ref<string>('')
const initSelectOptions = () => {
    const result: any[] = []
    for (const value in foodTypeMap) {
        // @ts-ignore
        const label = foodTypeMap[value]
        result.push({
            label,
            value
        })
    }
    selectOptions.value = result
}
initSelectOptions()

const selectChange = (value: string | undefined) => {
    console.log('🌈 —— data-value --->', value)
}

const handleKeydown = (event: Event | KeyboardEvent) => {
    if ((event as KeyboardEvent).code === 'Enter') {
        initQueryList()
    }
}

const handleSearch = () => {
    initQueryList()
}

// edit
const isEdit = ref<boolean>(false)
const handleEdit = (scope: any) => {
    isEdit.value = true
    const row = scope.scope.row
    Object.assign(form, row)
    drawerOpen.value = true
}

// 点击删除
const handleDel = async (id: number) => {
    await deleteFood({ id })
    ElMessage({
        type: 'success',
        message: '删除成功'
    })
    await initQueryList()
}

// 添加项的抽屉
const drawerOpen = ref<boolean>(false)
const formInstance = ref<FormInstance>()
const form = reactive<FoodFormType>({
    name: '',
    loveType: '',
    foodType: '',
    description: ''
})
const rules = reactive<FormRules<FoodFormType>>({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    loveType: [{ required: true, message: '请选择喜爱程度', trigger: 'blur' }],
    foodType: [{ required: true, message: '请选择食物类型', trigger: 'blur' }]
})

// 关闭抽屉
const cancelDrawer = () => {
    if (!formInstance.value) return
    formInstance.value.clearValidate()
    drawerOpen.value = false
}

const loveSelects = ref<any[]>([])
const typeSelects = ref<any[]>([])

const initLoveSelects = () => {
    const result: any[] = []
    for (const value in foodLoveTypeMap) {
        // @ts-ignore
        const label = foodLoveTypeMap[value]
        result.push({
            label,
            value
        })
    }
    loveSelects.value = result
}
initLoveSelects()

const initTypeSelects = () => {
    const result: any[] = []
    for (const value in foodTypeMap) {
        // @ts-ignore
        const label = foodTypeMap[value]
        result.push({
            label,
            value
        })
    }
    typeSelects.value = result
}
initTypeSelects()

// 对新增或更新进行分发
const confirm = () => {
    if (!formInstance.value) return
    formInstance.value.validate((valid: boolean, fields) => {
        if (!valid) {
            console.error(fields)
            return
        }
        if (isEdit.value) {
            updateHandler()
        } else {
            addHandler()
        }
    })
}

// 新增
const addHandler = async () => {
    await insertFood(form)
    ElMessage({
        type: 'success',
        message: '添加成功'
    })
    drawerOpen.value = false
    await initQueryList()
}

const updateHandler = async () => {
    await updateFood(form)
    ElMessage({
        type: 'success',
        message: '更新成功'
    })
    drawerOpen.value = false
    await initQueryList()
}

const beforeModule = () => {
    Object.assign(form, {
        name: '',
        loveType: '',
        foodType: '',
        description: ''
    })
    isEdit.value = false
    drawerOpen.value = true
}
</script>

<template>
    <div class="love-container base-card">
        <div class="search-container">
            <div class="edit-area">
                <ElButton type="danger"> 批量删除 </ElButton>
                <ElButton
                    type="primary"
                    @click="beforeModule"
                >
                    添加
                </ElButton>
            </div>
            <div class="search-area">
                <ElSelect
                    placeholder="请选择食物类型"
                    style="width: 160px"
                    v-model="selected"
                    clearable
                    @change="selectChange"
                >
                    <el-option
                        v-for="item in selectOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </ElSelect>
                <ElInput
                    placeholder="请输入名称搜索"
                    style="width: 200px"
                    v-model="keyword"
                    maxlength="10"
                    clearable
                    @keydown="handleKeydown"
                >
                    <template #append>
                        <ElButton
                            :icon="Search"
                            @click="handleSearch"
                        />
                    </template>
                </ElInput>
            </div>
        </div>
        <div class="table-container">
            <AdminTable
                :columns="foodColumns"
                :initial="foodList"
                border
                :is-pagination="false"
                :is-selected="true"
                index
            >
                <template #edit="scope">
                    <ElButton
                        plain
                        type="primary"
                        @click="handleEdit(scope)"
                    >
                        编辑
                    </ElButton>
                    <ElButton
                        plain
                        type="danger"
                        @click="handleDel(scope.scope.row.id)"
                    >
                        删除
                    </ElButton>
                </template>
            </AdminTable>
        </div>
        <!-- 抽屉 -->
        <ElDrawer
            v-model="drawerOpen"
            :title="isEdit ? '更新' : '新增'"
            @close="cancelDrawer"
        >
            <ElForm
                ref="formInstance"
                :model="form"
                :rules="rules"
                label-width="auto"
                label-position="top"
            >
                <ElFormItem
                    label="名称"
                    prop="name"
                >
                    <ElInput
                        placeholder="请输入名称"
                        v-model.trim="form.name"
                    />
                </ElFormItem>
                <ElFormItem
                    label="喜爱程度"
                    prop="loveType"
                >
                    <ElSelect
                        placeholder="请选择喜爱程度"
                        v-model="form.loveType"
                    >
                        <el-option
                            v-for="item in loveSelects"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </ElSelect>
                </ElFormItem>
                <ElFormItem
                    label="类型"
                    prop="foodType"
                >
                    <ElSelect
                        placeholder="请选择类型"
                        v-model="form.foodType"
                    >
                        <el-option
                            v-for="item in typeSelects"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </ElSelect>
                </ElFormItem>
                <ElFormItem
                    label="描述"
                    prop="description"
                >
                    <ElInput
                        type="textarea"
                        placeholder="请输入描述"
                        v-model.trim="form.description"
                        :rows="3"
                    />
                </ElFormItem>
            </ElForm>
            <div class="footer-btn-group">
                <ElButton @click="cancelDrawer">取消</ElButton>
                <ElButton
                    type="primary"
                    @click="confirm"
                >
                    {{ isEdit ? '更新' : '添加' }}
                </ElButton>
            </div>
        </ElDrawer>
    </div>
</template>

<style scoped lang="scss">
.love-container {
    .search-container {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8px;

        .edit-area {
            width: 50%;
            height: inherit;
            display: flex;
            align-items: center;
        }

        .search-area {
            width: 50%;
            height: inherit;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 12px;
        }
    }

    .table-container {
        width: 100%;
        height: calc(100% - 48px);
    }

    .footer-btn-group {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>
